package com.xjw.weixin;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;

import net.sf.json.JSONObject;

import com.xjw.util.HttpUtil;
import com.xjw.util.MessageType;
import com.xjw.util.SystemSetting;

public class WebChatSertlet extends HttpServlet {

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		ServletOutputStream out = response.getOutputStream();
		String bindUser = request.getParameter("bindUser");
		String aciton = request.getParameter("action");
		HttpSession session = request.getSession();
		if ("bindFrom".equals(aciton)) {
			
			if (StringUtils.isNotBlank(bindUser)) {
				session.setAttribute("openId", bindUser);
				String token = SystemSetting.getToken();
				JSONObject object = HttpUtil.httpGet(SystemSetting.URL_GET_USER.replace("ACCESS_TOKEN", token).replace("OPENID", bindUser));
				session.setAttribute("nickname", object.get("nickname"));
			}
			response.sendRedirect("bindUser.jsp");
		}else if ("bind".equals(aciton)) {
			String cardId = request.getParameter("cardId");
			if (cardId.length() > 4) {
				cardId = cardId.substring(cardId.length()-4);
			}
			Object o = session.getAttribute("openId");
			if (o != null) {
				String openId = o.toString();
				SystemSetting.bindMap.put(openId, cardId);
				out.write("绑定成功".getBytes("utf-8"));
			}else{
				out.write("绑定失败".getBytes("utf-8"));
			}
		}else if ("unbind".equals(aciton)) {
			SystemSetting.bindMap.remove(bindUser.toString());
			out.write("解除绑定成功".getBytes("utf-8"));
		}
		
		out.flush();
		out.close();
	}
}
